package com.zwps.biz.domain.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwps.biz.api.model.vo.fourpipes.PubCommonFileVO;
import com.zwps.biz.api.model.vo.structure.ZIdentificationPlateVO;
import com.zwps.biz.dal.db.dao.PubCommonFileDAO;
import com.zwps.biz.dal.db.dao.ZSafetyAppraisalDAO;
import com.zwps.biz.dal.db.object.ZSafetyAppraisalDO;

import com.zwps.biz.domain.service.ZSafetyAppraisalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@DS("lhk")
@Service
public class ZSafetyAppraisalServiceImpl extends ServiceImpl<ZSafetyAppraisalDAO, ZSafetyAppraisalDO>
        implements ZSafetyAppraisalService {

    @Autowired
    PubCommonFileDAO pubCommonFileDAO;
    @Override
    public ZSafetyAppraisalDO getSafetyAppraisal(String year) {
        ZSafetyAppraisalDO appraisalDO = this.getOne(new LambdaQueryWrapper<ZSafetyAppraisalDO>().eq(ZSafetyAppraisalDO:: getIsDelete,0).apply(year != null && !year.isEmpty(), "YEAR(authenticate_time) = {0}", year)  // 如果 year 不为空，才添加年份条件
                .last("LIMIT 1"));
        return appraisalDO != null ? appraisalDO : new ZSafetyAppraisalDO();
    }

    @Override
    public List<PubCommonFileVO> getSafetyAppraisalFile(String year) {
        LambdaQueryWrapper<ZSafetyAppraisalDO> wrapper = new LambdaQueryWrapper<ZSafetyAppraisalDO>()
                .eq(ZSafetyAppraisalDO::getIsDelete, 0);

        if (StringUtils.isNotBlank(year)) {
            try {
                wrapper.apply("YEAR(authenticate_time) = {0}", Integer.parseInt(year));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("年份格式不正确: " + year);
            }
        }

        List<ZSafetyAppraisalDO> appraisalDOList = this.list(wrapper);

        // 2. 提取所有文件URL
        List<String> fileUrls = appraisalDOList.stream()
                .map(ZSafetyAppraisalDO::getFileUrl)
                .filter(StringUtils::isNotBlank)
                .flatMap(fileUrl -> Arrays.stream(fileUrl.split(",")))
                .map(String::trim)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        // 3. 如果没有文件URL，返回空列表
        if (CollectionUtils.isEmpty(fileUrls)) {
            return Collections.emptyList();
        }

      return pubCommonFileDAO.getFileByUrls(fileUrls);
    }


}




